package org.zjvis.datascience.common.algo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zjvis.datascience.common.constant.SqlTemplate;
import org.zjvis.datascience.common.enums.AlgEnum;
import org.zjvis.datascience.common.enums.SubTypeEnum;
import org.zjvis.datascience.common.sql.SqlHelper;
import org.zjvis.datascience.common.util.ToolUtil;
import org.zjvis.datascience.common.vo.TaskVO;

import java.util.List;

/**
 * @description Locally Linear Embedding 降维算子模板类
 * @date 2021-12-24
 */
public class LLEAlg extends BaseAlg {

    private final static Logger logger = LoggerFactory.getLogger("LLEAlg");

    private static String TPL_FILENAME = "template/algo/lle.json";

    private static String SQL_TPL = "SELECT * FROM \"%s\".\"lle\"('%s', '%s', '%s', '%s', %s, %s)";

    private static String SQL_TPL_MADLIB_SAMPLE = "SELECT * FROM \"%s\".\"lle\"('CREATE VIEW %s AS SELECT * from %s where \"%s\" <= %s', '%s', '%s', '%s', %s, %s)";

    public void initTemplate(JSONObject data) {
        JSONArray jsonArray = getTemplateParamList(TPL_FILENAME);
        data.put("setParams", jsonArray);
        baseInitTemplate(data);
        JSONArray validate = new JSONArray();
        validate.add("feature_cols,number");
        data.put("validate", validate);
    }

    public LLEAlg() {
        super(AlgEnum.LLE.name(), SubTypeEnum.DIMENSION_REDUCTION.getVal(), SubTypeEnum.DIMENSION_REDUCTION.getDesc());
        this.maxParentNumber = 1;
    }

    private String getLLESql(String sourceTable, String outTable, String featureCols, int k, int neighbors, String sampleTable) {
        if (StringUtils.isNotEmpty(sampleTable)) {
            return String.format(SQL_TPL_MADLIB_SAMPLE, SqlTemplate.SCHEMA,
                    sampleTable, sourceTable, ID_COL, SAMPLE_NUMBER, outTable, ID_COL, featureCols, k, neighbors);
        } else {
            //TODO  没有对应spark的包装算法
            return String.format(SQL_TPL, SqlTemplate.SCHEMA, sourceTable, outTable, ID_COL, featureCols, k, neighbors);
        }
    }

    public String initSql(JSONObject json, List<SqlHelper> sqlHelpers, long timeStamp, String engineName) {
        this.engineName = engineName;
        String sourceTable = json.getString("source_table");
        sourceTable = ToolUtil.alignTableName(sourceTable, timeStamp);
        String outTable = json.getString("out_table_rename");
        outTable = ToolUtil.alignTableName(outTable, timeStamp);
        int k = json.getInteger("dimension_num");
        JSONArray features = json.getJSONArray("feature_cols");
        String featureCols = this.getFeatureColsStr(features);
        int neighbors = json.getInteger("neighbors");
        String sampleTable = "";
        if (!json.containsKey("isSample") || json.getString("isSample").equals("SUCCESS") || json.getString("isSample").equals("FAIL")) {
            sampleTable = outTable.replace("solid_", "view_");
            json.put("isSample", "CREATE");
        }
        String sql = this.getLLESql(sourceTable, outTable, featureCols, k, neighbors, sampleTable);
        logger.debug("sql={}", sql);
        return sql;
    }

    public void defineOutput(TaskVO vo) {
        JSONObject jsonObject = vo.getData();
        String outTablePrefix = jsonObject.getString("out_table");
        String tableName = String.format(SqlTemplate.OUT_TABLE_NAME, outTablePrefix, vo.getPipelineId(), vo.getId());
        jsonObject.put("out_table_rename", tableName);
        JSONArray input = jsonObject.getJSONArray("input");
        if (input == null || input.size() == 0) {
            logger.warn("input is empty");
            return;
        }
        this.checkBoxSelectFilter(jsonObject, "number", FEATURE_COLS);
        this.supplementForCheckbox(jsonObject, TPL_FILENAME, 1, vo);
        jsonObject.put("source_table", input.getJSONObject(0).getString("tableName"));

        JSONArray outputColTypes = new JSONArray();
        JSONArray outputCols = new JSONArray();
        outputCols.add(ID_COL);
        outputColTypes.add(ID_TYPE);
        if (!jsonObject.containsKey("dimension_num")) {
            vo.setData(jsonObject);
            return;
        }
        Integer k = jsonObject.getInteger("dimension_num");
        for (int i = 0; i < k; ++i) {
            outputCols.add(String.format("f%s", i + 1));
            outputColTypes.add("numeric");
        }
        JSONArray output = new JSONArray();
        JSONObject outItem = new JSONObject();
        outItem.put("tableName", tableName);
        outItem.put("nodeName", vo.getName() == null ? AlgEnum.LLE.toString() : vo.getName());
        outItem.put("tableCols", outputCols);
        outItem.put("columnTypes", outputColTypes);
        this.setSubTypeForOutput(outItem);
        output.add(outItem);
        jsonObject.put("output", output);
        vo.setData(jsonObject);
    }
}
